package com.qys.livesMall.file.server.upload.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.file.server.upload.mapper.VideoStoreMapper;
import com.qys.livesMall.file.server.upload.model.entity.VideoStore;
import com.qys.livesMall.file.server.upload.service.VideoStoreService;
import com.qys.livesMall.framework.view.BaseQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * 视频库 服务实现类
 * </p>
 *
 * @author
 * @since 2023-05-30
 */
@Slf4j
@Service
public class VideoStoreServiceImpl extends ServiceImpl<VideoStoreMapper, VideoStore> implements VideoStoreService {

    @Async
    @Override
    public CompletableFuture<String> addFileToVideoStore(String fileNamePath) {
        VideoStore store = new VideoStore();
        store.setUrl(fileNamePath);
        store.setCreateTime(LocalDateTime.now());
        baseMapper.insert(store);
        return CompletableFuture.completedFuture("insert success");
    }

    /**
     * 更新视频图片到视频库
     *
     * @param videoPath 视频地址
     * @param imgPath   图片地址
     * @param type      上传类型
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateImageUrlToVideoStore(String videoPath, String imgPath, String type) {
        VideoStore store;

        if (null != videoPath) {
            store = baseMapper.selectOne(Wrappers.<VideoStore>query().eq("url", videoPath));
            if (null == store) {
                log.error("未从视频库获取到视频信息:{}", videoPath);
                return;
            }
        } else {
            store = new VideoStore();
        }

        store.setImgUrl(imgPath);
        store.setType(type);
        saveOrUpdate(store);
    }

    /**
     * 分页查询视频库信息
     *
     * @param baseQuery
     */
    @Override
    public Page<VideoStore> page(BaseQuery baseQuery) {
        QueryWrapper<VideoStore> wrapper = Wrappers.query();
        if (Objects.isNull(baseQuery.getId())) {
            wrapper.eq("id", baseQuery.getId());
        }
        wrapper.orderByDesc("create_time");

        return baseMapper.selectPage(new Page<>(baseQuery.getPageNum(), baseQuery.getPageSize()), wrapper);
    }
}
